package com.vancouver.knows.ui.fragment.my;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.BuildConfig;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.QueryUserInfoTaskMark;
import com.vancouver.knows.ui.activity.MainActivity;
import com.vancouver.knows.ui.activity.citydiscount.QrCodeActivity;
import com.vancouver.knows.ui.activity.citydiscount.QrCodeBusinessActivity;
import com.vancouver.knows.ui.activity.login.LoginActivity;
import com.vancouver.knows.ui.activity.my.EditProfileActivity;
import com.vancouver.knows.ui.activity.my.MyAtcommentActivity;
import com.vancouver.knows.ui.activity.my.MyCommentActivity;
import com.vancouver.knows.ui.activity.my.MyFeedbackAboutProcotolActivity;
import com.vancouver.knows.ui.activity.my.MyFollowedActivity;
import com.vancouver.knows.ui.activity.my.MyPointsActivity;
import com.vancouver.knows.ui.activity.my.MyUserPostCommentsActivity;
import com.vancouver.knows.ui.activity.my.ResetPasswordActivity;
import com.vancouver.knows.ui.activity.my.SelectWindow;
import com.vancouver.knows.ui.activity.set.MessageRemindActivity;
import com.vancouver.knows.ui.activity.userpost.UserPostListsActivity;
import com.vancouver.knows.ui.base.BaseFragment;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.CircleTransform;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Chris Li on 2016-07-21.
 */
public class NewUserFragment extends BaseFragment implements IResultReceiver, MenuAdapter.OnMenuItemClickListener, View.OnClickListener {

    private static Context context;
    private static final String TAG = NewUserFragment.class.getSimpleName();
    private final int CLEAR_CACHE = 1;
    private static final int ABOUT_US = 3;
    private static final int TERMS_OF_SERVICE = 4;

    @Bind(R.id.scroll_view)
    NestedScrollView mScrollView;
    @Bind(R.id.toolbar_title)
    TextView mToolbarTitle;
    @Bind(R.id.user_image)
    ImageView mUserImage;
    @Bind(R.id.user_name)
    TextView mUsername;
    @Bind(R.id.user_join_date)
    TextView mUserJoinDate;
    @Bind(R.id.post_count)
    TextView mPostCount;
    @Bind(R.id.watch_count)
    TextView mWatchCount;
    @Bind(R.id.user_menu_list)
    RecyclerView mUserMenuList;
    @Bind(R.id.app_version)
    TextView mAppVersion;

    private BSharedPrefManager mSharedPrefManager;
    private String[] mAttrTitles;
    private SelectWindow mClearCacheDialog;

    private MenuAdapter mMenuAdapter;
    private OnNotificationUpdateListener mNotificationUpdateListener;

    public static NewUserFragment newInstance() {
        return new NewUserFragment();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = getActivity();
        mAttrTitles = getActivity().getResources().getStringArray(R.array.my_list_titles);
        return inflater.inflate(R.layout.fragment_user, container, false);
    }

    @Override
    protected void bindView(View rootView) {

        mClearCacheDialog = new SelectWindow(getActivity(), this, getString(R.string.sure_cache), getString(R.string.cache));

        mUserMenuList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mUserMenuList.setNestedScrollingEnabled(false);
        mMenuAdapter = new MenuAdapter(getActivity(), createMenuItems());
        mMenuAdapter.setListener(this);
        mUserMenuList.setAdapter(mMenuAdapter);

        mSharedPrefManager = imContext.getSharedPrefManager();

        if (mSharedPrefManager.getUserId() != null) {
            setupUserView();
        } else {
            setupDefaultView();
        }

        mAppVersion.setText(getString(R.string.app_version, BuildConfig.VERSION_NAME, String.valueOf(BuildConfig.VERSION_CODE)));
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof OnNotificationUpdateListener) {
            mNotificationUpdateListener = (OnNotificationUpdateListener) context;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mSharedPrefManager != null && mSharedPrefManager.getUserId() != null) {
            QueryUserInfoTaskMark taskMark = bModule.getTaskMarkPool().getQueryUserInfoTaskMark();
            bModule.getServiceWrapper().queryUserInfo(this, taskMark, mSharedPrefManager.getUserId());
            setNotifications();
        } else {
            setupDefaultView();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        //赋空
        context = null;
    }

    private void setupUserView() {
        UserInfo.UserMeta userMeta = mSharedPrefManager.getUserMeta();
        if (userMeta != null) {
            Picasso.with(getActivity()).load(userMeta.getAvatar()).transform(new CircleTransform())
                    .fit().centerCrop().into(mUserImage);
        } else {
            Picasso.with(getActivity()).load(R.drawable.me_icon_login).transform(new CircleTransform())
                    .fit().into(mUserImage);
        }
        mToolbarTitle.setText(mSharedPrefManager.getUserName());
        mUsername.setText(mSharedPrefManager.getUserName());
        if (mSharedPrefManager.getTotalPostsCount() != null) {
            mPostCount.setText(mSharedPrefManager.getTotalPostsCount());
        }
        if (mSharedPrefManager.getTotalWatchingCount() != null) {
            mWatchCount.setText(mSharedPrefManager.getTotalWatchingCount());
        }
        if (mSharedPrefManager.getRegisterDate() != null) {
            mUserJoinDate.setText(getString(R.string.join_date, AppUtils.getEventPdg(mSharedPrefManager.getRegisterDate())));
        }
    }

    private void setupDefaultView() {
        Picasso.with(getActivity()).load(R.drawable.me_icon_login).transform(new CircleTransform())
                .fit().into(mUserImage);
        mToolbarTitle.setText(R.string.my_title);
        mUsername.setText(R.string.user_login_text);
        mPostCount.setText("0");
        mWatchCount.setText("0");
        mUserJoinDate.setText("");
    }

    private List<MenuAdapter.MenuItem> createMenuItems() {
        List<MenuAdapter.MenuItem> menuItems = new ArrayList<>();

        menuItems.add(new MenuAdapter.MenuItem(0, R.string.menu_group_title_me, MenuAdapter.MenuItem.MENU_ITEM_HEADER));
        menuItems.add(new MenuAdapter.MenuItem(R.drawable.qrcode, R.string.menu_item_fl_qrcode, MenuAdapter.MenuItem.MENU_ITEM_DEFAULT));
        menuItems.add(new MenuAdapter.MenuItem(R.drawable.draft_icon, R.string.menu_item_drafts, MenuAdapter.MenuItem.MENU_ITEM_DEFAULT));

        MenuAdapter.MenuItem postCommentsMenuItem = new MenuAdapter.MenuItem(R.drawable.note_icon, R.string.menu_item_classified_post_comments, MenuAdapter.MenuItem.MENU_ITEM_DEFAULT);
        postCommentsMenuItem.setHasNotification(true);
        menuItems.add(postCommentsMenuItem);

        menuItems.add(new MenuAdapter.MenuItem(R.drawable.sms_icon, R.string.menu_item_posted_comments, MenuAdapter.MenuItem.MENU_ITEM_DEFAULT));

        MenuAdapter.MenuItem atCommentsMenuItem = new MenuAdapter.MenuItem(R.drawable.email_icon, R.string.menu_item_comments_mentioned_me, MenuAdapter.MenuItem.MENU_ITEM_DEFAULT);
        atCommentsMenuItem.setHasNotification(true);
        menuItems.add(atCommentsMenuItem);

        menuItems.add(new MenuAdapter.MenuItem(R.drawable.pig_icon, R.string.menu_item_collected_points, MenuAdapter.MenuItem.MENU_ITEM_DEFAULT));
        menuItems.add(new MenuAdapter.MenuItem(R.drawable.bookmark_icon, R.string.menu_item_business_concerns, MenuAdapter.MenuItem.MENU_ITEM_DEFAULT));
        menuItems.add(new MenuAdapter.MenuItem(R.drawable.photos_icon, R.string.menu_item_photos, MenuAdapter.MenuItem.MENU_ITEM_DEFAULT));
        menuItems.add(new MenuAdapter.MenuItem(0, R.string.menu_group_title_settings, MenuAdapter.MenuItem.MENU_ITEM_HEADER));
        //menuItems.add(new MenuAdapter.MenuItem(R.drawable.translate_icon, R.string.menu_item_language_switch, MenuAdapter.MenuItem.MENU_ITEM_NORMAL));
        menuItems.add(new MenuAdapter.MenuItem(R.drawable.password_icon, R.string.menu_item_change_password, MenuAdapter.MenuItem.MENU_ITEM_NORMAL));
        menuItems.add(new MenuAdapter.MenuItem(R.drawable.reminder_icon, R.string.menu_item_notifications, MenuAdapter.MenuItem.MENU_ITEM_NORMAL));
        menuItems.add(new MenuAdapter.MenuItem(0, R.string.menu_group_title_on, MenuAdapter.MenuItem.MENU_ITEM_HEADER));
        menuItems.add(new MenuAdapter.MenuItem(R.drawable.astronaut_icon, R.string.menu_item_about_us, MenuAdapter.MenuItem.MENU_ITEM_NORMAL));
        menuItems.add(new MenuAdapter.MenuItem(R.drawable.about_icon, R.string.menu_item_tos, MenuAdapter.MenuItem.MENU_ITEM_NORMAL));
        //menuItems.add(new MenuAdapter.MenuItem(R.drawable.help_icon, R.string.menu_item_help, MenuAdapter.MenuItem.MENU_ITEM_NORMAL));

        return menuItems;
    }


    private void setNotifications() {
        if (mSharedPrefManager != null && mSharedPrefManager.getUserId() != null) {
            if (mSharedPrefManager.getCloseAllMessage()) {
                if (mSharedPrefManager.getMyArticleNewComment() && !mSharedPrefManager.getTotalUnReadPostComment().equals("0")) {
                    mMenuAdapter.setNotification(R.string.menu_item_classified_post_comments, mSharedPrefManager.getTotalUnReadPostComment());
                } else {
                    mMenuAdapter.setNotification(R.string.menu_item_classified_post_comments, "0");
                }

                if (mSharedPrefManager.getHaveAtCommentMessage() && !mSharedPrefManager.getTotalUnReadComment().equals("0")) {
                    mMenuAdapter.setNotification(R.string.menu_item_comments_mentioned_me, mSharedPrefManager.getTotalUnReadComment());
                } else {
                    mMenuAdapter.setNotification(R.string.menu_item_comments_mentioned_me, "0");
                }
            }
        } else {
            mMenuAdapter.resetNotifications();
        }

        if (mNotificationUpdateListener != null) {
            mNotificationUpdateListener.onNotificationUpdate();
        }
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
        if (exception == null) {
            if (isAdded()) {
                setupUserView();
                setNotifications();
            }
        } else {
            Log.e(TAG, exception.getExMessage());
        }
    }

    public void scrollUp() {
        if (mScrollView != null) {
            mScrollView.scrollTo(0, 0);
        }
    }

    @OnClick({R.id.user_image, R.id.edit_profile})
    public void onEditUserProfile() {
        if (getLoginStatus()) {
            Intent intent = new Intent(getActivity(), EditProfileActivity.class);
            startActivity(intent);
        }
    }

    @OnClick({R.id.post_count_container, R.id.watch_count_container})
    public void onCountContainersClicked(View view) {

        switch (view.getId()) {

            case R.id.post_count_container: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), UserPostListsActivity.class);
                    intent.putExtra(UserPostListsActivity.VIEW_EXTRA, UserPostListsActivity.HISTORY_VIEW);
                    startActivity(intent);
                }
            }
                break;

            case R.id.watch_count_container: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), UserPostListsActivity.class);
                    intent.putExtra(UserPostListsActivity.VIEW_EXTRA, UserPostListsActivity.FOLLOWING_VIEW);
                    startActivity(intent);
                }
            }
                break;
        }
    }

    @OnClick(R.id.clear_cache_button)
    public void onClearCacheButtonClicked() {
        mClearCacheDialog.show();
    }

    @Override
    public void onMenuItemClicked(MenuAdapter.MenuItem menuItem) {
        switch (menuItem.getTitleResource()) {
            case R.string.menu_item_fl_qrcode:
                //福利二维码
                getActivity().startActivity(new Intent(getActivity(), QrCodeActivity.class));
                break;

            case R.string.menu_item_drafts: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), UserPostListsActivity.class);
                    intent.putExtra(UserPostListsActivity.VIEW_EXTRA, UserPostListsActivity.HISTORY_VIEW);
                    intent.putExtra(UserPostListsActivity.IS_DRAFT_EXTRA, true);
                    startActivity(intent);
                }
            }
                break;

            case R.string.menu_item_classified_post_comments: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), MyUserPostCommentsActivity.class);
                    intent.putExtra("MY_TITLE", getActivity().getString(R.string.menu_item_classified_post_comments));
                    startActivity(intent);
                }
            }
                break;

            case R.string.menu_item_posted_comments: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), MyCommentActivity.class);
                    intent.putExtra("MY_TITLE", getActivity().getString(R.string.my_comment));
                    startActivity(intent);
                }
            }
                break;

            case R.string.menu_item_comments_mentioned_me: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), MyAtcommentActivity.class);
                    intent.putExtra("MY_TITLE", "@" + getActivity().getString(R.string.my_comment));
                    startActivity(intent);
                }
            }
                break;

            case R.string.menu_item_collected_points: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), MyPointsActivity.class);
                    intent.putExtra("MY_TITLE", getActivity().getString(R.string.my_points));
                    startActivity(intent);
                }
            }
                break;

            case R.string.menu_item_business_concerns: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), MyFollowedActivity.class);
                    intent.putExtra("MY_TITLE", getActivity().getString(R.string.my_attention));
                    intent.putExtra("TAB_INDEX", 3);
                    startActivity(intent);
                }
            }
                break;

            case R.string.menu_item_photos: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), UserImageGalleryActivity.class);
                    startActivity(intent);
                }
            }
                break;

            case R.string.menu_item_language_switch:

                break;

            case R.string.menu_item_change_password: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), ResetPasswordActivity.class);
                    startActivity(intent);
                }
            }
                break;

            case R.string.menu_item_notifications: {
                if (getLoginStatus()) {
                    Intent intent = new Intent(getActivity(), MessageRemindActivity.class);
                    intent.putExtra("COMMON_TIPS", getActivity().getString(R.string.message_title));
                    startActivity(intent);
                }
            }
                break;

            case R.string.menu_item_about_us: {
                Intent intent = new Intent(getActivity(), MyFeedbackAboutProcotolActivity.class);
                intent.putExtra("USER_NOTICE", mAttrTitles[ABOUT_US]);
                intent.putExtra("PAGE_TYPE", "about_us");
                startActivity(intent);
            }
                break;

            case R.string.menu_item_tos: {
                Intent intent = new Intent(getActivity(), MyFeedbackAboutProcotolActivity.class);
                intent.putExtra("USER_NOTICE", mAttrTitles[TERMS_OF_SERVICE]);
                intent.putExtra("PAGE_TYPE", "user_terms");
                startActivity(intent);
            }
                break;

            case R.string.menu_item_help:

                break;
        }
    }

    private boolean getLoginStatus() {
        if (mSharedPrefManager.getUserId() != null) {
            return true;
        } else {
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return false;
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.sure:
                mClearCacheDialog.dismiss();
                AppUtils.clearImageDiskCache(getActivity());
                Toast.makeText(getActivity(), getActivity().getString(R.string.cached), Toast.LENGTH_SHORT).show();
                break;
        }
    }

    public interface OnNotificationUpdateListener {
        void onNotificationUpdate();
    }

    public static void showCityDiscountTab() {
        if ( context != null)
           ((MainActivity)context).showCityDiscountTab();
    }
}
